package com.sdry.product.sorting.controller;
import	java.util.HashSet;
import	java.util.ArrayList;
import java.util.Date;
import java.sql.Timestamp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.Container;
import com.sdry.basic.entity.Material;
import com.sdry.basic.entity.ProductionStation;
import com.sdry.basic.entity.WarehousesRegionLocation;
import com.sdry.common.BaseAPIMessageTypeEnum;
import com.sdry.common.BaseController;
import com.sdry.common.BaseTypeEnum;
import com.sdry.common.ResultAppInfo;
import com.sdry.exception.BizException;
import com.sdry.product.common.entity.ProductInverted;
import com.sdry.product.common.mapper.ProductInvertedMapper;
import com.sdry.product.common.service.ProductInvertedService;
import com.sdry.product.prod.entity.LacquerInto;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.sorting.entity.SortFrame;
import com.sdry.product.sorting.entity.SortReceiving;
import com.sdry.product.sorting.entity.SortReceivingDetail;
import com.sdry.product.sorting.entity.SortingApp;
import com.sdry.product.sorting.service.SortReceivingDetailService;
import com.sdry.product.sorting.service.SortingAppService;
import com.sdry.product.sorting.service.SortingStockService;
import com.sdry.transit.entity.TransitLoadingDetail;
import com.sdry.transit.entity.TransitOrder;
import com.sdry.transit.service.TransitOrderService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 分拣区app接口
 * @author chenBin
 * @date 2020年3月16日 15:49:03
 * @version 1.0
 */
@RestController
@RequestMapping(value = "sortingApp")
public class SortingAppController extends BaseController {
    /***中转区*/
    @Resource
    TransitOrderService transitOrderService;
    @Resource
    private SortingAppService sortingAppService;
    @Resource
    private SortingStockService sortingStockService;
    /*** 倒框倒架服务对象*/
    @Resource
    private ProductInvertedService productInvertedService;

    //////////////////////////////卸车收货/////////////////////////////////////////////

    /**
     * 中转区——生产指令--编号
     * @param param 编号
     * @return List<TransitOrder>
     */
    @RequestMapping(value = "/api/queryTransitOrderNumber")
    public List<TransitOrder> queryTransitOrderNumber(TransitOrder param) {
        logger.info("根据条件查询所有条件"+ JSONArray.fromObject(param));
        List<TransitOrder> transitOrderList = transitOrderService.queryAllByMution(param);
        return transitOrderList;
    }

    /**
     * 查询卸车收货的生产单据查询
     * @return
     */
    @RequestMapping(value = "/api/queryTransitLoadingDetailNumber")
    public ResultAppInfo queryTransitLoadingDetailNumber() {
        logger.info("查询卸车收货的生产单据查询");
        List<SortingApp> list = sortingAppService.queryTransitLoadingDetailNumber();
        return getResultAppInfo("1",list,"");
    }

    /**
     * 查询容器通用编号
     * @param carNumber 车牌号
     * @param toNumber 单据编号
     * @return ResultAppInfo
     */
    @RequestMapping(value = "/api/queryBaseContainerNumber")
    public ResultAppInfo querySortingContainerNumber(String carNumber,String toNumber) {
        logger.info("查询容器分拣区卸车收货编号  车牌号carNumber" +carNumber +" toNumber = "+toNumber);
        List<ProductionStation> productionStations = sortingAppService.querySortingContainerNumber(carNumber,toNumber);
        return getResultAppInfo("1",productionStations,"");
    }

    /**
     * 查询容器中物料
     * @param psnumber 容器ID
     * @return ResultAppInfo
     */
    @RequestMapping(value = "/api/queryBaseContainerMaterielList")
    public ResultAppInfo queryBaseContainerMaterielList(String psnumber, HttpServletRequest request) {
        logger.info("查询容器中物料","containerId = " +psnumber);
        if (StringUtils.isBlank(psnumber)) {
           return getResultAppInfo("0",null, BaseAPIMessageTypeEnum.A006.getName());
        }
        try {
        String[] psNumbers = psnumber.split(",");
            List<ResultAppList<Material>>  resultAppListList = sortingAppService.queryBaseContainerMaterielList(psNumbers);
        return getResultAppInfo("1",resultAppListList,"");
        } catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
    }

    /**
     * 卸车收货提交
     * @param json 提交数据
     */
    @RequestMapping(value = "/api/addSortingAppReceiving")
    public ResultAppInfo addSortingAppReceiving(String json,String userId) {
        logger.info("卸车收货提交", json,userId);
        try {
            sortingAppService.addSortingAppReceiving(json,userId);
        } catch (BizException e){
            return getResultAppInfo("0",null,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
        return getResultAppInfo("1",null,"");
    }

    /////////////////////////////入分拣区//////////////////////////////////////////////////

    /**
     * 查询入分拣区，框编号
     * @return
     */
    @RequestMapping(value = "/api/querySortingReceivingNumber")
    public Map<String,Object> queryReceivingContainerNumber(HttpServletRequest request) {
        logger.info("查询入分拣区，框编号");
        //查询框编号
        List<Container> containerList = sortingAppService.queryBaseContainerNumber();
        /////////////////////////////////查询库位////////////////////////////////////////
        String typeNumber = BaseTypeEnum.FJ.getCode();
        List<WarehousesRegionLocation> warehousesRegionLocationList = sortingAppService.queryBaseWarehousesRegionLocationNumber(typeNumber);
        Map<String,Object> result = new HashMap<>();
        result.put("containerNumber",containerList);
        result.put("storehouseNumber",warehousesRegionLocationList);
        return getResultAppLogin("1",result,"",request.getParameter("token"));
    }

    /**
     * 入分拣区物料查询
     * @param psnumber 框编号
     * @return
     */
    @RequestMapping(value = "/api/querySortingReceivingNumberMaterielList")
    @ResponseBody
    public ResultAppInfo querySortingReceivingNumberMaterielList(String psnumber) {
        List<ResultAppList<Material>>  resultAppListList = sortingAppService.querySortingReceivingNumberMaterielList(psnumber);
        return getResultAppInfo("1",resultAppListList,"");
    }

    /**
     * 入分拣区提交
     * @param libraryId  库位ID
     * @param containerIds 数组容器ID
     * @param userId 用户ID
     */
    @RequestMapping(value = "/api/addSoringFrame")
    public ResultAppInfo addSoringFrame(
            @RequestParam(value = "libraryId") String libraryId,
            @RequestParam String containerIds,
            @RequestParam(value = "userId")String userId) {

        try {
            logger.info("入分拣区提交", "containerIds = " + containerIds);
            sortingAppService.addSoringFrame(libraryId, containerIds, userId);
        }catch (BizException e){
            return getResultAppInfo("0",null,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
        return getResultAppInfo("1",null,"");
    }

    /////////////////////////////////物料倒框//////////////////////////////////////////////////////////

    /**
     * 查询容器中物料包括空的铁框
     * @param psnumber 容器ID
     * @return ResultAppInfo
     */
    @RequestMapping(value = "/api/queryBaseContainerMaterielListAndEmpty")
    public ResultAppInfo queryBaseContainerMaterielListAndEmpty(String psnumber) {
        logger.info("查询容器中物料包括空的铁框","containerId = " +psnumber);
        try {
            String[] psNumbers = psnumber.split(",");
            List<ResultAppList<Material>>  resultAppListList = sortingAppService.queryBaseContainerMaterielListAndEmpty(psNumbers);
            return getResultAppInfo("1",resultAppListList,"");
        } catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
    }


    /**
     * 根据库存查询，分拣区倒框记录铁框（工位）查询
     */
    @RequestMapping(value = "/api/queryBaseContainerNumberByStock")
    public ResultAppInfo queryBaseContainerNumberByStock() {
        logger.info("据库存查询，分拣区倒框记录铁框（工位）查询 -- /api/queryBaseContainerNumberByStock");
        QueryWrapper<SortFrame> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status","0");
        List<SortFrame> sortFrameList = sortingStockService.list(queryWrapper);
        for (SortFrame sortFrame : sortFrameList) {
            Container container = sortingStockService.queryContainer(sortFrame.getContainerId());
            if (container == null) {
               continue;
            }
            sortFrame.setContainerNumber(container.getCnumber());
            if (sortFrame.getContainerNumber() == null) {
                continue;
            }
        }
        Set<SortFrame> sortFrames = new HashSet<> ();
        for (SortFrame sortFrame : sortFrameList) {
            if (sortFrame.getContainerNumber() != null) {
                sortFrames.add(sortFrame);
            }
        }
        List<SortFrame> sortFrames1 = new ArrayList<> ();
        sortFrames1.addAll(sortFrames);
        return getResultAppInfo("1",sortFrames1,"");
    }

    /**
     * 倒框或者倒架添加（提交）
     */
    @RequestMapping(value = "/api/addProductInverted")
    public ResultAppInfo addProductInverted(String json,String userId) {
        logger.info("倒框或者倒架添加（提交） -- /api/addProductInverted");
        try {
            productInvertedService.addProductInverted(json,userId);
        }catch (BizException e){
            return getResultAppInfo("0",null,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
        return getResultAppInfo("1",null,"");
    }

    ////////////////////////////////装车发货///////////////////////////////////////////////
    @RequestMapping(value = "/api/queryWorkshop")
    public Map<String,Object> queryWorkshop(HttpServletRequest request) {
        logger.info("分拣区---装车发货 --- /api/queryWorkshop");
        //查询框编号
        List<Container> containerList = sortingAppService.querySortingFrameNumber();
        /////////////////////////////////查询库位////////////////////////////////////////
        JSONArray json = new JSONArray();

        String qcl1 = BaseTypeEnum.getNameByCode("QCL");
        String qcl2 = BaseTypeEnum.getNameByCode("YG");
        String qcl3 = BaseTypeEnum.getNameByCode("PT");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("wrlnumber",qcl1);
        jsonObject1.put("code","QCL");

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("wrlnumber",qcl2);
        jsonObject2.put("code","YG");

        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("wrlnumber",qcl3);
        jsonObject3.put("code","PT");

        json.add(jsonObject1);
        json.add(jsonObject2);
        json.add(jsonObject3);

        Map<String,Object> result = new HashMap<>();
        result.put("containerNumber",containerList);
        result.put("storehouseNumber",json);
        return getResultAppLogin("1",result,"",request.getParameter("token"));
    }

    /**
     * 装车发货物料查询
     * @param psnumber 框编号
     * @return
     */
    @RequestMapping(value = "/api/querySortingOutMaterielList")
    @ResponseBody
    public ResultAppInfo querySortingOutMaterielList(String psnumber) {
        List<ResultAppList<Material>>  resultAppListList = sortingAppService.addSortingOutMaterielList(psnumber);
        return getResultAppInfo("1",resultAppListList,"");
    }

    /**
     * 扫描出分拣区（提交）
     */
    @RequestMapping(value = "/api/addSortingOutStock")
    public ResultAppInfo addSortingOutStock(
            @RequestParam(value = "libraryId") String libraryId,
            @RequestParam String containerIds,
            @RequestParam(value = "userId")String userId) {
        try {
            sortingAppService.addSortingOutStock(libraryId,containerIds,userId);
        }catch (BizException e){
            return getResultAppInfo("0",null,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return getResultAppInfo("0",null,BaseAPIMessageTypeEnum.A001.getName());
        }
        return getResultAppInfo("1",null,"");
    }
}
